const path = require('path')
const fs = require('fs-extra')
const { genDir, logger } = require('../utils')
const underPackagesDirPath = file => path.resolve(__dirname, '../../packages', file)
const Create = require('./create')
let targetDirs = process.argv.slice(2)

//确保传入了文件目录参数
if (!targetDirs.length) {
  return logger.error('cannot find dir name, try yarn run genFile ${dirname} again')
}
targetDirs = targetDirs.map(f => underPackagesDirPath(f))
const checkDirExist = async fileDir => await fs.pathExists(fileDir)
const loopAndOpAllDirs = (callback, dirs) => {
  const result = []
  for (const dir of dirs) {
    const promise = callback(dir)
    result.push(promise)
  }
  return Promise.all(result)
}

//确保文件不重复
const result = []
loopAndOpAllDirs(checkDirExist, targetDirs).then(async arrRes => {
  for (let index = 0; index < arrRes.length; index++) {
    if (arrRes[index]) {
      return logger.error(
        `${targetDirs[index]} is existing under packages dir, please rename or remove it and try again`
      )
    } else {
      //生成文件目录
      try {
        await genDir(targetDirs[index])
        result.push(new Create().create(targetDirs[index]))
        Promise.all(result).then(res => {
          logger.info('generate file success ,checkout package directory')
        })
      } catch (error) {
        logger.error(error)
      }
    }
  }
})
